const {
	Service
} = require("uni-cloud-router");
const {
	result_success,
	result_error
} = require('http-result-modle')
const {
	payNotifyUrl
} = require('config-current-space')
const db = uniCloud.database()
let wmzAlipaySdk = uniCloud.importObject('wmz-alipay-sdk')
const unipay = require('uni-pay')
module.exports = class AlipayService extends(
	Service
) {
	/**
	 * 获取openid
	 * @param {Object} code
	 */
	async getAlipayOpenId(app_id, code) {
		let params = {
			app_id: app_id,
			url: 'alipay.system.oauth.token',
			params: {
				grant_type: "authorization_code",
				code: code
			}
		}
		return await wmzAlipaySdk.alipayRequestCommon(params)
	}

	async pay(app_id, openid, out_trade_no, total_amount, subject, notify_url, noprofitsharing) {
		let data = await this.service.applet.getAppletInfoById(app_id)
		let op_app_id = data.alipay.auth_app_id
		if (data.alipay.auth_app_id === data.alipay.template_id) {
			/* app_id = "41d77edc652396eb060b99d651807e76"
			op_app_id ="2021004120681924" */
			data.alipay.noprofitsharing = true
		}
		if(data.account_type==='qyk'){
			data.alipay.noprofitsharing = true
		}
		/* if (data.alipay.pay_app_id) {
			app_id = data.alipay.pay_app_id
			op_app_id = data.alipay.pay_auth_app_id
		} */
		let userInfo= await db.collection('uni-id-users').where({
			openid:openid
		}).get()
		userInfo=userInfo.data[0]
		if(userInfo.login_appId){
			app_id = userInfo.login_appId
			op_app_id = userInfo.login_pay_appId
		}else if (data.alipay.pay_app_id) {
			app_id = data.alipay.pay_app_id
			op_app_id = data.alipay.pay_auth_app_id
		}
		let sys_service_provider_id = data.alipay.isv_pid

		let biz_content = {
			out_trade_no: out_trade_no,
			total_amount: total_amount / 100,
			subject: subject,
			product_code: 'JSAPI_PAY',
			op_app_id: op_app_id,
			extend_params: {
				sys_service_provider_id: sys_service_provider_id
			}
		}
		if(openid.length===16){
			biz_content.buyer_id=openid
		}else{
			biz_content.buyer_open_id=openid
		}
		if (app_id != "41d77edc652396eb060b99d651807e76" && !data.alipay.noprofitsharing) {
			if (data.alipay.profitsharing) {
				if (total_amount > 300) {
					if (!noprofitsharing) {
						biz_content.extend_params.royalty_freeze = true
					}
				}
			} else {
				return result_error("支付权限错误")
			}
		}
		let tpayNotifyUrl="https://fc-mp-d84e928e-2b27-4fa9-b240-63574c62e78a.next.bspapp.com/"
		let params = {
			app_id: app_id,
			url: 'alipay.trade.create',
			biz_content: biz_content,
			params: {
				notify_url: payNotifyUrl + notify_url
			}
		}
		console.log(params)
		let result = await wmzAlipaySdk.alipayRequestCommon(params)
		console.log(result)
		if (result.code === 200) {
			return result_success(result.data.tradeNo)
		} else {
			return result_error(result.msg)
		}
	}

	async payApp(app_id, openid, outTradeNo, totalFee, subject, notify_url) {
		let unipayIns = unipay.initAlipay({
			mchId: "2088341855742340",
			appId: "2021004123607289",
			alipayPublicKey: "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlFpfs8kw7a9NbPG2TQp4Xo638EUqfRAgVZzQIS8BRQKxFWSQMDE3m7upD3o1mkeNg3LE7htCFZTqYLrkV2TcGdteYb8MAztDICf5YC/rpEr+PQHosvoCCLyaKZThm9bkyfxfkjyHznx/4XlvZhlQkKu9Y6MQLTV4WxbhlYMgOaqBf4HEO63y9me7KOqqbi7gyeAmCpumRG3w26tAthztSxv4rIkbzI4xjxQ2DtVEUMAc7L7ps4S7WjJKh/nkjLwRsUbyAOvkhqAKgUxVjsmJuF75BYUbfO8OKZLlUZXe8Q+nDdE/Ur9kyhS+/dou/5LyrPtbLX5S5IEu2EuxLdkgmQIDAQAB",
			privateKey: "MIIEpAIBAAKCAQEAmQft48bt+Lytdf0cOcxr9jJ1BM2j0yXGOSPV54aKNpws8wPcVXOCgQmXIMIme6kJYPH9FI+t6z4BPpqHsDeVerz4w42S/ivyeu9cZMm5eFZMJHSbFAB2ugWvTS4zNGlSx7grZQofZDMjlrHPm4N84slOnKB6zR8YYHsM44WhxbonOhTG9JJ4QF9abhqb9/A8lV9Swc4tj1Yj3rEahzI8lKTlwQPUExn4Y3Dh6RkxTPmeLS6H3Dx8XpX59s7pbz5jqfGtp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of0VKtm2Gid0SnJU0/FB1f2QD5tmHv/5zVsScBQobsnCEpnFISC4ocQKBgQDAjV0YIr8M92KuwfMlx8FLvAjt1NIX3yLni+5KJSf8hTZkb2CU5sGHt2yzDEL94XP+Z0RmTJDWFTy/bA8wdY44Qtz5jYUQzC8+VTu/RRVJR404F/3vqPYTqZ4vnwT/JR4dnBTVqHPxb468LnZ5FB9XnDuQQC6jbi9Ldjg9bYtsZA==",
			keyType: 'PKCS1'
		});
		let clienIp = this.ctx.context.CLIENTIP
		let orderInfo = await unipayIns.getOrderInfo({
			subject: subject, // 微信支付时不可填写此项
			body: subject,
			outTradeNo: outTradeNo,
			totalFee: totalFee, // 金额，单位分
			notifyUrl: payNotifyUrl + notify_url, // 支付结果通知地址
			spbillCreateIp: clienIp,
			tradeType: "APP" 
		})
		return result_success(orderInfo)
	}
};